#!C:\perl\bin
use strict;
use warnings;
use lib "/perl/lib";
use Spreadsheet::ParseExcel;
use DBI;
use utf8;
use Encode;

#fonction qui permet de remplir les tables pour les valeurs narrow et wide
sub create_test{ 
	#id_type_test, id_anim, datet, exp result2
	my @tab=@_;

	my @id_test2;
	my @id_res2;
	my @id_type_test;
	my $id_anim;
	my $datet;
	my @res;
	my $dbh;
	my $exp;
	
	foreach (my $val=0; $val<=$#tab; $val++){
		if($val<5){
			push(@id_type_test,$tab[$val]);
		}
		elsif($val eq 5){
			$id_anim=$tab[$val];
		}
		elsif($val eq 6){
			$datet=$tab[$val];
		}
		elsif($val eq 7){
			$dbh=$tab[$val];
		}
		elsif($val eq 8){
			$exp=$tab[$val];
		}
		else{
			push(@res,$tab[$val]);
		}
	}
	
	# ************************************* Création test ************************************* #

	### verification que le test n'existe pas deja ###
	my $prep_test=$dbh->prepare("SELECT id_test FROM Test WHERE experimentateur='$exp' AND id_type_test=? AND date_test=(E'$datet')");
	foreach my $k(@id_type_test){
		$prep_test->execute($k);
		while (my @val=$prep_test->fetchrow_array()){
			push(@id_test2,$val[0]);
		}
		$prep_test->finish();
	}
	
	### ajout du test si il n'existe pas ###
	if(not @id_test2){
		foreach my $l(@id_type_test){
			$dbh->do("INSERT INTO Test(date_test, experimentateur, id_type_test) VALUES ('$datet', '$exp', $l)");
			$prep_test->execute($l);
			while (my @val=$prep_test->fetchrow_array()){
				push(@id_test2,$val[0]);
			}
			$prep_test->finish();
			
		}
	}
	
			
	# ************************************* Création resultat_test ************************************* #
	
	### vérification que resultat_test n'existe pas ###
	my $prep_rtest=$dbh->prepare("SELECT id_res from resultat_test WHERE id_test=? and id_animal=$id_anim");
	foreach my $i(@id_test2){
		$prep_rtest->execute($i);
		while (my @val=$prep_rtest->fetchrow_array()){
			push(@id_res2,$val[0]);
		}
		$prep_rtest->finish();
	}
	
	if(not @id_res2){
		foreach my $l(@id_test2){
			$dbh->do("INSERT INTO Resultat_test(id_test, id_animal) VALUES($l, $id_anim)");
			$prep_rtest->execute($l);
			while (my @val=$prep_rtest->fetchrow_array()){
				push(@id_res2,$val[0]);
			}
			$prep_rtest->finish();
		}
	}
	
	# ************************************* Création resultat_test_simple ************************************* #
	
	my $prep_resultat=$dbh->prepare("SELECT id_res FROM resultat_test_simple WHERE mesure=? AND id_res=?");

	for(my $elt=0; $elt<=$#res; $elt++){
		for(my $elt2=0; $elt2<=$#id_res2; $elt2++){
			if( $elt eq $elt2){
				$prep_resultat->execute($res[$elt],$id_res2[$elt2]);
				my @val=$prep_resultat->fetchrow_array();
				my $size3=@val;
				$prep_test->finish();
				if($size3 eq 0 and $res[$elt] ne ''){ #si l'animal est resté au centre
					$dbh->do("INSERT INTO Resultat_test_simple(id_res, mesure) VALUES($id_res2[$elt2], $res[$elt])");					
				}
			}
		}
	}	
	return 0;
}



# **************************** Récupération des données ***************************** #

# il ne doit pas y avoir de fiche type ou fiche bilan en feuille de début de fichier #

my $fichier=$ARGV[0];
my $exp=encode_utf8($ARGV[1]); 
$exp=~s/_/\ /;
my $parser=Spreadsheet::ParseExcel->new();
my $workbook=$parser->parse("$fichier");
if (!defined $workbook){
    die $parser->error(),".\n";
}

my $worksheet;
my %result;

foreach($workbook->worksheets()){
	my $microcebe;
	my %infos;
	$worksheet=$_;
	my $naissance;
	my $date;
	my %date_test;
	
	my $micro=$worksheet->get_name();
	my @mic=split('#',$micro);
	$microcebe=$mic[1];
	
	my ($row_min,$row_max) = $worksheet->row_range();
	my ($col_min, $col_max) = $worksheet->col_range();
	

	
	for my $row ($row_min .. $row_max){ #parcours lignes
	my @narrow;
	my @wide;
		
		for my $col ($col_min .. $col_max){ #parcours colonnes
			if ($col eq 1 and $row eq 0) { #recup date naissance
				my $cont=$worksheet->get_cell($row,$col);
				$naissance=$cont->value();
			}
			
			if ($row>2){
				if ($col eq 0){
					my $cont=$worksheet->get_cell($row,$col);
					if ($cont){
						$date=$cont->value();
					}
				}
				if($date){				
					if($col>=6 and $col<=10){
						my $cont=$worksheet->get_cell($row,$col);
						push(@narrow,$cont->value());
					}
					if($col>=13 and $col<=17){
						my $cont=$worksheet->get_cell($row,$col);
						push(@wide,$cont->value());
					}
				}
			}
			
		}
		if($date and @narrow and @wide){
			$date_test{'narrow'}=\@narrow;
			$date_test{'wide'}=\@wide;
		}
		
		if($date){
			$infos{'naissance'}=$naissance;
			$infos{$date}={%date_test};
			%date_test=();
		}
		
	}
	$result{$microcebe}={%infos};
}

#~ my $util;
#~ my $util2;
#~ foreach $util (keys %result) {
	#~ print "\n\n$util : \n";
    #~ foreach $util2 (keys %{$result{$util}}) {
		#~ if($util2 ne 'naissance'){
			#~ print "$util2\n";
			#~ foreach (keys %{$result{$util}{$util2}}){
				#~ print "$_ -> $result{$util}{$util2}{$_}[0], $result{$util}{$util2}{$_}[1],$result{$util}{$util2}{$_}[2],$result{$util}{$util2}{$_}[3],$result{$util}{$util2}{$_}[4]\n";
			#~ }
		#~ }
		#~ else{
			#~ print "naissance: $result{$util}{$util2}\n";
		#~ }
    #~ }
#~ }



# ********************* INSERTION DONNEES DANS LA BASE **************************** #

# connection a sql
my $dbh=DBI->connect("DBI:Pg:dbname='mmdn';host=localhost","postgres","mmdn",{'RaiseError'=>1});
# execute INSERT query


# ************************************* Création type_test ************************************* #

my @unite_mesure=('T1','T2','T3','T4','T5');
my @id_type_test_narrow;
my @id_type_test_wide;

#pour hourglass narrow
my $narrow=$dbh->prepare("SELECT id_type_test FROM type_test WHERE label='Test comportemental' AND description='Hourglass narrow' AND unite_mesure=?");
foreach my $elt(@unite_mesure){
	$narrow->execute($elt);
	while(my @unite=$narrow->fetchrow_array()){
		push(@id_type_test_narrow,$unite[0]);
	}
	$narrow->finish();
}
if(not @id_type_test_narrow){
	foreach my $elt(@unite_mesure){
		$dbh->do("INSERT INTO Type_test(label, description,unite_mesure) VALUES ('Test comportemental', 'Hourglass narrow', '$elt')"); 
		$narrow->execute($elt);
		while(my @unite=$narrow->fetchrow_array()){
			push(@id_type_test_narrow,$unite[0]);
		}
		$narrow->finish();
	}
}

#pour hourglass wide
my $wide=$dbh->prepare("SELECT id_type_test FROM type_test WHERE label='Test comportemental' AND description='Hourglass wide' AND unite_mesure=?");
foreach my $elt(@unite_mesure){
	$wide->execute($elt);
	while(my @unite=$wide->fetchrow_array()){
		push(@id_type_test_wide,$unite[0]);
	}
	$wide->finish();
}
if(not @id_type_test_wide){
	foreach my $elt(@unite_mesure){
		$dbh->do("INSERT INTO Type_test(label, description,unite_mesure) VALUES ('Test comportemental', 'Hourglass wide', '$elt')"); 
		$wide->execute($elt);
		while(my @unite=$wide->fetchrow_array()){
			push(@id_type_test_wide,$unite[0]);
		}
		$wide->finish();
	}
}

		
foreach my $code (keys %result) { #$code =code_animal
	#recuperation du code_animal et de sa date de naissance =>creation de l'animal
	my $date=$result{$code}{'naissance'};
	my $id_anim;
	my @tab;

	# ************************************* Création animal ************************************* #
	
	### verification de l'existence de l'animal dans la base
	my $temp=$dbh->prepare("SELECT distinct(id_animal,date_naissance) FROM Animal WHERE code_animal=(E'$code')");
	$temp->execute();
	while (my @val=$temp->fetchrow_array()){
		push(@tab,$val[0]);
	}
	$temp->finish();
	
	my $size=@tab;
	if($size eq 0){ #aucun animal n'existe avec ce code
		$dbh->do("INSERT INTO Animal(code_animal,date_naissance) VALUES ('$code','$date')");
		$id_anim=$dbh->selectrow_array("SELECT id_animal FROM Animal WHERE code_animal=(E'$code') and date_naissance=(E'$date')");
	}
	elsif($size eq 1){ #un seul animal existe avec ce code, on vérifie que les dates de naissance correspondent
		foreach my $i(@tab){
			my @temp=split(',',$i);
			my $id=$temp[0];
			$id=~s/\(//; #id trouvé
			my $nai=$temp[1];
			$nai=~s/\)//; #date de naissance trouvée
			if($nai ne ''){ #si l'animal existant a une date de naissance
				if($nai eq $date){ #on vérifie que les dates coïncident
					$id_anim=$id;
					last;
				}
				else{ #si elles ne coïncident pas, on créé un nouvel animal
					$dbh->do("INSERT INTO Animal(code_animal,date_naissance) VALUES ('$code','$date')");
					$id_anim=$dbh->selectrow_array("SELECT id_animal FROM Animal WHERE code_animal=(E'$code') and date_naissance=(E'$date')");
					last;
				}
			}
			else{ #si l'animal existant n'a pas de date de naissance, on l'update
				$dbh->do("UPDATE Animal SET date_naissance=(E'$date') WHERE id_animal=$id");
				$id_anim=$id;
			}
		}
	}
	elsif($size>1){ #s'il existe plusieurs animaux avec ce code
		foreach my $i(@tab){
			my @temp=split(',',$i);
			my $id=$temp[0];
			$id=~s/\(//; #id trouvé
			my $nai=$temp[1];
			$nai=~s/\)//; #date de naissance trouvée
			if($nai ne ' '){ #si l'animal existant a une date de naissance
				if($nai eq $date){ #on vérifie que les dates coïncident
					$id_anim=$id;
					last;
				}
			}
			elsif($nai eq ' '){ #si l'animal trouvé n'a pas de date de naissance, on lui en met une
				$dbh->do("UPDATE Animal SET date_naissance=(E'$date') WHERE id_animal=$id");
				$id_anim=$id;
				last;
			}
		}
		if(not $id_anim){ #si aucune date ne correspond, on créé un nouvel animal
			$dbh->do("INSERT INTO Animal(code_animal,date_naissance) VALUES ('$code','$date')");
			$id_anim=$dbh->selectrow_array("SELECT id_animal FROM Animal WHERE code_animal=(E'$code') and date_naissance=(E'$date')");
		}
	}

	foreach my $key (keys %{$result{$code}}) {
		if ($key ne 'naissance'){
			my $datet=$key; #date du test
			
			
			foreach (keys %{$result{$code}{$key}}){
				my @result2;
				for my $i(0 .. 4){
					push(@result2,$result{$code}{$key}{$_}[$i]); 
				}
				if($_ eq 'narrow'){
					&create_test(@id_type_test_narrow,$id_anim,$datet,$dbh,@result2);
				}
				else{
					&create_test(@id_type_test_wide,$id_anim,$datet,$dbh,@result2);
				}
			}			
		}
	}
}

$dbh->disconnect();
